<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html>
<html lang="en">
<head>
<title><s:message code="app.title" /></title>
<%@ include file="Include.jsp"%>
<script type="text/javascript">
	
	$(document).ready(function() {
		var oTable = $('#shippingBillTable').dataTable( {
			 	"bDestroy": true,
		        "bProcessing": false,
		        "iDisplayLength": 10,
		        "bFilter": false,
		        "bLengthChange": false,
		        "aoColumnDefs": [
		          { 'bSortable': false, 'aTargets': [2] }
		       	]
		 	} );
		
		$("input[id='sbillno']").typeahead({
             source: function(query, process) {
				return getShippingBill("sbillno="+query, process);
            },
            updater: function(item){
            	return populateShippingBill(item);
		    },
		    
			items : 4, minLength : 1
        });
		
	});
	
	/**
	 * This method will make an AJAX call to retrieve ShippingBill No Details and Display AJAX Based Typeahead in called
	 * text field. 
	 */
	function getShippingBill(query,process){
		return $.ajax({
			type: "GET",
			url: "ShippingbilLAutoComplete",
			data: ""+query,
			dataType: "json",
			success: function (json) {
				var sourceArr = [];

				$.map(json, function(product) {
					sourceArr.push(product.sbillNo);
					return "\""+product.sbillNo+"\"";
				});
				
				process(sourceArr);
			}
		});
	}
	
	function populateShippingBill(item){
		$("input[id='sbillno']").val(item.substring(item.lastIndexOf("-")+1));
		getShippingBillDetails(item);
		return item;
	}
	
	/**
     * All data regarding Shipping Bill number will be set.
     
     */
     function getShippingBillDetails(item){
    	$.ajax({
			type: "GET",
			url: "ShippingbilLAutoComplete",
			data: "sbillno="+item,
			dataType: "json",
			success: function (response) {
				
				var jsonList = response;
	   	 		if(jsonList != null){
	   	 			for (var i = 0; i < jsonList.length; i++){

	   	 				$('#directhubid').val(jsonList[i].directhubid);
	   	 				$('#invoiceno').val(jsonList[i].invoiceno);
		   	 			$('#invoicedate').val(jsonList[i].invoicedateString);
			   	 		$('#invoicepayterms').val(jsonList[i].invoicepayterms);
				   	 	$('#sbilldate').val(jsonList[i].sbilldateString);
					   	$('#fobvalueinr').val(jsonList[i].fobvalueinr);
					   	$('#incotermsid').val(jsonList[i].incotermsid);
					   	$('#currencyid').val(jsonList[i].currencyid);
					   	$('#invoicevalue').val(jsonList[i].invoicevalue);	
	   	
	   	 			}
	   	 		}
	   	 		
			},
			error:  function (json) {
				
				$('#directhubid').val('');
	 			$('#invoiceno').val('');
   	 			$('#invoicedate').val('');
	   	 		$('#invoicepayterms').val('');
		   	 	$('#sbilldate').val('');
			   	$('#fobvalueinr').val('');
			   	$('#incotermsid').val('');
			   	$('#currencyid').val('');
			   	$('#invoicevalue').val('');
			}
		});
	 }
	
	function edit(jobnoid,sbId,shippingContainerId){
		$('#shippingBillEditForm').attr('action','EditShippingBill?jobnoId='+jobnoid+'&sbId='+sbId+'&shippingContainerId='+shippingContainerId);
		
		$('#shippingBillEditForm #sbId').val(sbId);
		$('#shippingBillEditForm #shippingContainerId').val(shippingContainerId);
		$('#shippingBillEditForm #jobnoId').val(jobnoid);
		
		$('#shippingBillEditForm').attr('method','get');
		$('#shippingBillEditForm').submit();
	}
	
	function addNewShippingBill(jobnoid){
		$('#shippingBillAddForm').attr('action','ListShippingBill?jobnoId='+jobnoid);
		$('#shippingBillAddForm #jobnoId').val(jobnoid);
		
		$('#shippingBillAddForm').attr('method','get');
		$('#shippingBillAddForm').submit();
	}
	
	function clearFields(){

		var form = document.forms[2];
		var focusField = "NONE";				
		for( var i=0; i < form.length; i++ ){
			var field = form.elements[i];
			
			if( field.type == "text"){
				if( focusField == "NONE" ){
					focusField = field;
				}
				field.value = "";
			}
			if( field.type == "hidden"){
				if( focusField == "NONE" ){
					focusField = field;
				}
				field.value = "";
			}
			if( field.type == "select-one"){	
				if( focusField == "NONE" ){
					focusField = field;
				}		
				field.options[0].selected = true;
			}
			if( field.type == "select-multiple"){	
				if( focusField == "NONE" ){
					focusField = field;
				}		
				for(j=0;j<field.options.length;j++)
					field.options[j].selected = false;
			}
			
			if( field.type == "checkbox"){	
				if( focusField == "NONE" ){
					focusField = field;
				}		
				field.checked = false;
			}
			
			if( field.type == "radio"){
				if( focusField == "NONE" ){
					focusField = field;
				}		
				field.checked = false;
			}		
		}
		
		focusField.focus();
	}
	
	$(document).ready(function() {
		$.ajax({  
			type: "GET",  
			url: "ShippingbillContainerList",
			crossDomain: false,
			async : true,
	   	 	success: function(response) {
	   	 		var jsonList = response;
	   	 		var listItems= "<option value=''>SELECT</option>";
	   	 		if(jsonList != null){
	   	 			for (var i = 0; i < jsonList.length; i++){
	   	 				listItems+= "<option value='" + jsonList[i].fieldId + "'>" + jsonList[i].fieldname + "</option>";
	   	 			}
	   	 		}
	       		$("#containerCombobox").html(listItems);
	       		
	       		setContainer('${shippingbillForm.shippingcontainersForm.containerid}');
	       		setContainerCombobox();
	          	},
	          	
	   		error: function(result){
	   			var listItems= "<option value=''>--SELECT--</option>";
	   			$("#containerCombobox").html(listItems);
	    	}
		});
		
	} );
</script>
<style>
.custom-combobox {
	position: relative;
	display: inline-block;
}

.custom-combobox-toggle {
	position: absolute;
	top: 0;
	bottom: 0;
	margin-left: -1px;
	padding: 0;
	/* support: IE7 */
	*height: 1.7em;
	*top: 0.1em;
}

.custom-combobox-input {
	margin: 0;
	padding: 0.3em;
	width: 70%;
}
</style>
<script>
//function to set the selected value as default in container
function setContainer(value) {
	if (typeof (value) != 'undefined' && (value != null || value != '') ) {
		 $('#containerCombobox option').each(function () {
		        if (($(this).attr('value')) == value) {
		            $(this).attr('selected', 'selected');
		        }
		 });
	}
}

//function to set the Container Combobox
function setContainerCombobox() {
	$(function() {
		$.widget( "custom.combobox", {
			_create : function() {
				this.wrapper = $("<span>").addClass(
						"custom-combobox").insertAfter(
						this.element);
				this.element.hide();
				this._createAutocomplete();
				this._createShowAllButton();
			},
			_createAutocomplete : function() {
				var selected = this.element
						.children(":selected"), value = selected
						.val() ? selected.text() : "";
				this.input = $("<input>")
						.appendTo(this.wrapper)
						.val(value)
						.attr("title", "")
						.addClass(
								"custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
						.autocomplete({
							delay : 0,
							minLength : 0,
							source : $.proxy(this, "_source")
						}).tooltip({
							tooltipClass : "ui-state-highlight"
						});
				this._on(this.input, {
					autocompleteselect : function(event, ui) {
						ui.item.option.selected = true;
						this._trigger("select", event, {
							item : ui.item.option
						});
					},
					autocompletechange : "_removeIfInvalid"
				});
			},
			_createShowAllButton : function() {
				var input = this.input, wasOpen = false;
				$("<a>")
						.attr("tabIndex", -1)
						.appendTo(this.wrapper)
						.button({
									icons : {
										primary : "ui-icon-triangle-1-s"
									},
									text : false
								})
						.removeClass("ui-corner-all")
						.addClass(
								"custom-combobox-toggle ui-corner-right")
						.mousedown(
								function() {
									wasOpen = input
											.autocomplete(
													"widget")
											.is(":visible");
								}).click(function() {
							input.focus();
							// Close if already visible
							if (wasOpen) {
								return;
							}
							// Pass empty string as value to search for, displaying all results
							input.autocomplete("search", "");
						});
			},
			_source : function(request, response) {
				
			 var matcher = new RegExp($.ui.autocomplete
						.escapeRegex(request.term), "i");
				response(this.element
						.children("option")
						.map(
								function() {
									var text = $(this).text();
									if (this.value
											&& (!request.term || matcher
													.test(text)))
										return {
											label : text,
											value : text,
											option : this
										};
								}));
			},
			_removeIfInvalid : function(event, ui) {
				// Selected an item, nothing to do
				if (ui.item) {
					return;
				}
				// Search for a match (case-insensitive)
				var value = this.input.val(), valueLowerCase = value
						.toLowerCase(), valid = false;
				this.element
						.children("option")
						.each(
								function() {
									if ($(this).text()
											.toLowerCase() === valueLowerCase) {
										this.selected = valid = true;
										return false;
									}
								});
				// Found a match, nothing to do
				if (valid) {
					return;
				}
				// Remove invalid value
				this.input.val("").attr("title",
						value + " didn't match with any container")
						.tooltip("open");
				this.element.val("");
				this._delay(function() {
					this.input.tooltip("close").attr("title",
							"");
				}, 2500);
				this.input.data("ui-autocomplete").term = "";
			},
			_destroy : function() {
				this.wrapper.remove();
				this.element.show();
			}
		});
		
		$("#containerCombobox").combobox();
		$("#toggle").click(function() {
			$("#containerCombobox").toggle();
		});
		
	});
}
</script>
</head>
<body>
	<div class="container">
		<%@ include file="Menu.jsp"%>
		<h2><s:message code="shippingBillForm.addheader" /> (${jobregisterForm.jobno})</h2>
		<hr>
		<form:form id="cancelForm">
		</form:form>
		<form:form id="shippingBillAddForm">
			<input type="hidden" id="jobnoId" name="jobnoId" />
		</form:form>
		<form:form id="shippingBillEditForm" >
			<input type="hidden" id="sbId" name="sbId" />
			<input type="hidden" id="shippingContainerId" name="shippingContainerId" />
			<input type="hidden" id="jobnoId" name="jobnoId" />
		</form:form>
		
		<!--  Shipping Bill Add - Edit Code Start -->
		<form:form class="form-horizontal" method="post" name="shippingbillForm" id="shippingbillForm" commandName="shippingbillForm"
	           modelAttribute="shippingbillForm" >
	    	<form:errors cssClass="text-error" path="*" />       
	           
	        <form:hidden path="sbid" />
	        <form:hidden path="creationdate" />
			<c:if test="${not empty message}">
				<div class="alert alert-error">
					${message}
				</div>
			</c:if>
			<table class="table table-bordered">
				<tr>
					<form:hidden path="jobnoid" />
					<th><form:label path="cha"><s:message code="jobRegisterForm.chaid" /></form:label></th>
					<td>
						<s:message text="${jobregisterForm.cha}" />
					</td>
					<th><form:label path="directhubid"><s:message code="shippingBillForm.directhubid" /></form:label></th>
					<td>
						<form:select path="directhubid" cssClass="input-medium" tabindex="1" id="directhubid">
							<form:option value="">- Select -</form:option> 
							<form:options items="${directhubList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>
				</tr>
				<tr>
					<th><form:label path="invoiceno"><s:message code="shippingBillForm.invoiceno" /></form:label></th>
					<td>
						<form:input path="invoiceno" cssClass="input-medium" id="invoiceno" maxlength="30" size="50" tabindex="2"/>
					</td>
					<th><form:label path="invoicedate"><s:message code="shippingBillForm.invoicedate" /></form:label></th>
					<td>
						<form:input path="invoicedate" cssClass="input-medium" id="invoicedate" maxlength="10" size="20" tabindex="2" placeholder="DD/MM/YYYY"/>
					</td>
					<th><form:label path="invoicepayterms"><s:message code="shippingBillForm.invoicepayterms" /></form:label></th>
					<td>
						<form:input path="invoicepayterms" cssClass="input-large" id="invoicepayterms" maxlength="40" size="50" tabindex="2" placeholder="ie. 100% Adv.Payment"/>
					</td>		
				</tr>
				<tr>
					<th><form:label path="sbillno"><s:message code="shippingBillForm.sbillno" /></form:label></th>
					<td>
						<c:if test="${not empty shippingbillForm.sbid}">
							<form:input path="sbillno" cssClass="input-medium" id="sbillno" maxlength="7" size="20" tabindex="2"
						 		data-provide="typeahead" autocomplete="off" readonly="true"/>
						</c:if>
						
						<c:if test="${empty shippingbillForm.sbid}">
							<form:input path="sbillno" cssClass="input-medium" id="sbillno" maxlength="7" size="20" tabindex="2"
						 		data-provide="typeahead" autocomplete="off" />
						</c:if>
					</td>
					<th><form:label path="sbilldate"><s:message code="shippingBillForm.sbilldate" /></form:label></th>
					<td>
						<form:input path="sbilldate" cssClass="input-medium" id="sbilldate" maxlength="10" size="20" tabindex="2" placeholder="DD/MM/YYYY"/>
					</td>
					<th><form:label path="fobvalueinr"><s:message code="shippingBillForm.fobvalueinr" /></form:label></th>
					<td>
						<form:input path="fobvalueinr" cssClass="input-medium" id="fobvalueinr" maxlength="11" size="11" tabindex="2"/>
					</td>
				</tr>
				<tr>
					<th><form:label path="incotermsid"><s:message code="shippingBillForm.incotermsid" /></form:label></th>
					<td>
						<form:select path="incotermsid" cssClass="input-medium" tabindex="1" id="incotermsid">
							<form:option value="">- Select -</form:option> 
							<form:options items="${incotermsList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>					
					<th><form:label path="currencyid"><s:message code="shippingBillForm.currencyid" /></form:label></th>
					<td>
						<form:select path="currencyid" cssClass="input-medium" tabindex="1" id="currencyid">
							<form:option value="">- Select -</form:option> 
							<form:options items="${currencyList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>
					<th><form:label path="invoicevalue"><s:message code="shippingBillForm.invoicevalue" /></form:label></th>
					<td>
						<form:input path="invoicevalue" cssClass="input-medium" id="invoicevalue" maxlength="11" size="11" tabindex="2"/>
					</td>
				</tr>
			</table>
			
		<!--  Shipping Bill Add - Edit Code End -->
		
		<!--  Shipping Bill - Container Add - Edit Code Start -->
		<form:hidden path="shippingcontainersForm.shippingcontainerid" />
		<fieldset>
			<legend>
			<s:message code="shippingcontainersForm.addheader" />
			</legend>
			
			<table class="table table-bordered">
				<tr>
					<th><form:label path="shippingcontainersForm.containerid"><s:message code="shippingcontainersForm.container" />
						</form:label>
						</th>
					<td>
						<form:select path="shippingcontainersForm.containerid"  id="containerCombobox">
						</form:select>
					</td>
					<th><form:label path="shippingcontainersForm.noofpackages"><s:message code="shippingcontainersForm.noofpackages" />
						</form:label></th>
					<td>
						<form:input path="shippingcontainersForm.noofpackages" cssClass="input-small" id="noofpackages" maxlength="11" size="11" />
					</td>
					<th><form:label path="shippingcontainersForm.packagestypeid"><s:message code="shippingcontainersForm.packagestypeid" />
						</form:label>
						</th>
					<td>
						<form:select path="shippingcontainersForm.packagestypeid" cssClass="input-medium" >
							<form:option value="">- Select -</form:option> 
							<form:options items="${packagestypeList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>
				</tr>
				
				<tr>
					<th><form:label path="shippingcontainersForm.netweight"><s:message code="shippingcontainersForm.netweight" />
						</form:label></th>
					<td>
						<form:input path="shippingcontainersForm.netweight" cssClass="input-small" id="netweight" maxlength="11" size="11" />
					</td>
					
					<th><form:label path="shippingcontainersForm.netweightType"><s:message code="shippingcontainersForm.netweightid" />
						</form:label></th>
					<td>
						<form:select path="shippingcontainersForm.netweightType" cssClass="input-medium" >
							<form:option value="">- Select -</form:option> 
							<form:options items="${weighttypeList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>
					
					<th><form:label path="shippingcontainersForm.grossweight"><s:message code="shippingcontainersForm.grossweight" />
						</form:label></th>
					<td>
						<form:input path="shippingcontainersForm.grossweight" cssClass="input-small" id="grossweight" maxlength="11" size="11" />
					</td>
				</tr>
				
				<tr>
					<th><form:label path="shippingcontainersForm.grossweightType"><s:message code="shippingcontainersForm.grossweightid" />
						</form:label></th>
					<td>
						<form:select path="shippingcontainersForm.grossweightType" cssClass="input-medium" >
							<form:option value="">- Select -</form:option> 
							<form:options items="${weighttypeList}" itemLabel="formvalue" itemValue="codetableid" />
						</form:select>
					</td>
					
					<th><form:label path="shippingcontainersForm.cbm"><s:message code="shippingcontainersForm.cbm" />
						</form:label></th>
					<td>
						<form:input path="shippingcontainersForm.cbm" cssClass="input-small" id="cbm" maxlength="11" size="11" />
					</td>
					
					<th><form:label path="shippingcontainersForm.cargoreceiveddate"><s:message code="shippingcontainersForm.cargoreceiveddate" />
						</form:label></th>
					<td>
						<form:input path="shippingcontainersForm.cargoreceiveddate" cssClass="input-small" id="cargoreceiveddate" maxlength="11" 
							size="11" placeholder="DD/MM/YYYY" />
					</td>
				</tr>
				
			</table>	
			
		</fieldset>
			
		<!--  Shipping Bill - Container Add - Edit Code End -->
		
		<br/>
		<c:if test="${not empty shippingbillForm.sbid}">
				<button class="btn btn-primary" type="submit" formaction="EditShippingBill" formmethod="post" tabindex="7"><s:message code="app.add" /></button>
				<button class="btn" type="button" tabindex="8" onclick="addNewShippingBill('${param.jobnoId}')">
				<s:message code="shippingcontainersForm.addshippingBill" /></button>
			</c:if>
			<c:if test="${empty shippingbillForm.sbid}">
				<button class="btn btn-primary" type="submit" formaction="ListShippingBill" formmethod="post" tabindex="7"><s:message code="app.add" /></button>
			</c:if>
			&nbsp;
			<button class="btn" type="button" tabindex="8" onclick="clearFields();"> <s:message code="app.clear" /></button>
			&nbsp;
			<button class="btn" type="submit" formaction="ListJobRegister?jobid=${param.jobnoid}" form="cancelForm" formmethod="get" tabindex="9"><s:message code="app.cancel" /></button>
		
		</form:form>
		
		<!--  Shipping Bill List Code Start -->
		<table class="table table-hover table-bordered" id="shippingBillTable">
				<thead>
					<tr>
						<th><s:message code="shippingBillForm.sbillno" /></th>
						<th><s:message code="shippingBillForm.sbilldate" /></th>
						<th><s:message code="shippingcontainersList.containerNo" /></th>
						<th><s:message code="shippingcontainersList.agentSeal" /></th>
						<th><s:message code="shippingcontainersList.lineSeal" /></th>
						<th><s:message code="shippingcontainersList.noOfPkg" /></th>
						<th><s:message code="shippingcontainersList.pckgType" /></th>
						<th><s:message code="shippingcontainersList.groossWeight" /></th>
						<th><s:message code="shippingcontainersList.netWeight" /></th>
						<th><s:message code="shippingcontainersList.CBM" /></th>
						<th><s:message code="app.action" /></th>
					</tr>
				</thead>
				<tbody>
					<c:forEach items="${shippingBillList}" var="sb" >
						<tr>
							<td>
								<c:out value="${sb.sbillno}" />
							</td>
							<td>
								<c:out value="${sb.sbilldate}" />
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.container.containerno}">
									<c:if test="${not empty sb.shippingcontainersForm.containerType}">
										(<c:out value="${sb.shippingcontainersForm.container.containerno}" /> - 
										<c:out value="${sb.shippingcontainersForm.containerType}" />)
									</c:if>	
								</c:if>
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.container.agentsealno}">
									<c:out value="${sb.shippingcontainersForm.container.agentsealno}" />
								</c:if>
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.container.customsealno}">
									<c:out value="${sb.shippingcontainersForm.container.customsealno}" />
								</c:if>	
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.noofpackages}">
									<c:out value="${sb.shippingcontainersForm.noofpackages}" />
								</c:if>	
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.packageType}">
									<c:out value="${sb.shippingcontainersForm.packageType}" />
								</c:if>	
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.grossweight}">
									<c:out value="${sb.shippingcontainersForm.grossweight}" />
								</c:if>	
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.netweight}">
									<c:out value="${sb.shippingcontainersForm.netweight}" />
								</c:if>	
							</td>
							<td>
								<c:if test="${not empty sb.shippingcontainersForm.cbm}">
									<c:out value="${sb.shippingcontainersForm.cbm}" />
								</c:if>	
							</td>
							<td>
								<a href="#" onclick="javascript: edit('${sb.jobregister.jobnoid}','${sb.sbid}','${sb.shippingcontainersForm.shippingcontainerid}');" >
								Edit</a>
							</td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
	</div>
</body>
</html>